from binance.client import Client
import pandas as pd

import SecretData

api_key = SecretData.api_key
api_secret = SecretData.api_secret

client = Client(api_key, api_secret)

def get_klines(symbol, interval, limit=300):
    klines = client.get_klines(symbol=symbol, interval=interval, limit=limit)
    df = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume',
                                       'close_time', 'quote_asset_volume', 'number_of_trades',
                                       'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
    df = df.sort_values(by='timestamp').reset_index(drop=True)
    df['timestamp'] = range(1, len(df) + 1)  # 时间戳从1开始递增
    df.set_index('timestamp', inplace=True)
    return df[['high', 'low', 'volume']]  # 只保留最高价、最低价和成交量

if __name__ == '__main__':
    try:
        df = get_klines('BNBUSDT', Client.KLINE_INTERVAL_1HOUR)
        df.to_csv('../static/bnb_usdt_klines.csv')
        print("K线数据已保存到 bnb_usdt_klines.csv")
    except Exception as e:
        print(f"处理K线数据失败: {e}")
        raise
